package com.schoolvisitors;

import com.schoolvisitors.context.AdminContext;
import com.schoolvisitors.entity.Admin;
import com.schoolvisitors.enums.PermissionEnum;
import com.schoolvisitors.exception.ForbiddenException;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.response.ResultCode;
import com.schoolvisitors.service.AdminPermissionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private AdminPermissionService adminPermissionService;

    @Around("@annotation(checkPermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, CheckPermission checkPermission) throws Throwable {
        Admin admin = AdminContext.get();
        PermissionEnum requiredPermission = checkPermission.value();
        // 如果有超管权限直接通过
        if (adminPermissionService.hasPermission(admin, PermissionEnum.SYSTEM_ADMIN)){
            return joinPoint.proceed();
        }

        // 判断所需权限
        if (!adminPermissionService.hasPermission(admin, requiredPermission)) {
            // 返回统一权限错误响应
            throw new ForbiddenException("无权限访问");
        }

        // 有权限，继续执行目标方法
        return joinPoint.proceed();
    }
}

